package com.estar.assistsurvy.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.entity.ExperienceInfoList;
import com.estar.assistsurvy.entity.RequestQualificationPic;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.thread.QualificationPicThread;
import com.estar.assistsurvy.utils.Base64;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.FileUtils;
import com.estar.assistsurvy.utils.GlideUtiles;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.widget.NotScrollListview;
import com.estar.assistsurvy.widget.OptionPopwindow;
import com.estar.assistsurvy.widget.SelectPicPopupWindow;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class QualificationActivity extends BaseActivity implements OnClickListener{

	private TextView returnHome,industry_name;
	private LinearLayout select_industry,add_experience;
	private NotScrollListview experience_list;
	private ImageView take_photo,show_photo;
	private Button submit;
	private OptionPopwindow optionPop;
	private String[] options=new String[]{"公估人员","同业","社会人员"};
	private ArrayAdapter<String> adapter;
	private int num=0;
	private ArrayList<String> experiences;
	private Intent intent;
	private SelectPicPopupWindow ppw;
	private final static int GRAPH=0,ALBUM=1;
	private ArrayList<ExperienceInfoList> experienceInfoList;
	private String uuid,deviceId;
	private SharedPreferences preference;
	private Bitmap image;
	private long currentTime;
	private String picPath,certificatePhoto="";
	private String type="";
	private ProgressDialog dialog;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(dialog!=null){
				dialog.dismiss();
			}
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;
				
			case 0:
				ResponseMsg message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				if(message.getCode().equals("2")){
					ExitUtils.Unlogin(QualificationActivity.this, message.getMessages());
					return;
				}
				showShortToast(message.getMessages());
				intent=new Intent(QualificationActivity.this, CetificationActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_qualification);
		initView();
	}
	
	private void initView(){
		returnHome=find(R.id.returnBack);
		returnHome.setOnClickListener(this);
		select_industry=find(R.id.select_industry);
		select_industry.setOnClickListener(this);
		experience_list=find(R.id.experience_list);
		add_experience=find(R.id.add_experience);
		add_experience.setOnClickListener(this);
		take_photo=find(R.id.take_photo);
		take_photo.setOnClickListener(this);
		show_photo=find(R.id.show_photo);
		submit=find(R.id.submit);
		submit.setOnClickListener(this);
		industry_name=find(R.id.industry_name);
		experiences=new ArrayList<String>();
		adapter=new ArrayAdapter<>(QualificationActivity.this, R.layout.listview_experience, 
				R.id.experience_name, experiences);
		experience_list.setAdapter(adapter);
		
		experienceInfoList=new ArrayList<ExperienceInfoList>();
		preference=getSharedPreferences("user", MODE_PRIVATE);
		uuid=preference.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(QualificationActivity.this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			intent=new Intent(QualificationActivity.this, CetificationActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			break;
			
		case R.id.select_industry:
			optionPop=new OptionPopwindow(QualificationActivity.this, new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// TODO Auto-generated method stub
					industry_name.setText(options[position]);
					type=String.valueOf(position+1);
					optionPop.dismiss();
				}
			}, options);
			// 设置optionPop显示的位置
			optionPop.showAtLocation(QualificationActivity.this
					.findViewById(R.id.industry_name), Gravity.CENTER
					| Gravity.CENTER_HORIZONTAL, 0, -150);
			break;
			
		case R.id.add_experience:
			if(experienceInfoList.size()<10){

				intent=new Intent(QualificationActivity.this, AddExperienceActivity.class);
				startActivityForResult(intent, 2);
			}else{
				showShortToast("从业经历最多添加9条!");
			}
			
			break;
			
		case R.id.take_photo:
			selectPhoto();
			break;
			
		case R.id.submit:
			if(type.equals("")){
				showShortToast("请选择所属行业!");
				return;
			}
			if(certificatePhoto.equals("")){
				showShortToast("请添加资质照片!");
				return;
			}
			if(experienceInfoList==null||experienceInfoList.size()==0){
				showShortToast("请添加至少一条从业经历!");
				return;
			}
			dialog=ProgressDialog.show(this, null, "正在提交信息", false, false);

			RequestQualificationPic qualificationPic=new RequestQualificationPic(deviceId, uuid, type, certificatePhoto, experienceInfoList);
			new QualificationPicThread(QualificationActivity.this, handler, qualificationPic).start();
			break;

		default:
			break;
		}
	}
	
	private void selectPhoto(){
		ppw = new SelectPicPopupWindow(QualificationActivity.this,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 从相册获取图片
						intent=new Intent(Intent.ACTION_GET_CONTENT);
						intent.setType("image/*");  
						startActivityForResult(intent, ALBUM); 
						ppw.dismiss();
					}
				}, new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 从拍照获取图片
						intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						currentTime = System.currentTimeMillis();
						picPath=Environment
								.getExternalStorageDirectory()
								+ "/DCIM/"+"ESTAR"+currentTime + ".jpg";
						// 加载路径
						Uri uri = Uri.fromFile(new File(picPath));
						// 指定存储路径，这样就可以保存原图了
						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
						// 拍照返回图片
						startActivityForResult(intent, GRAPH);

						ppw.dismiss();
					}
				});
		// 设置ppw显示的位置
		ppw.showAtLocation(QualificationActivity.this
				.findViewById(R.id.take_photo), Gravity.CENTER
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==2 && resultCode==2){
			num++;
			if(num<10){
				experiences.add("经历"+num);
				adapter.notifyDataSetChanged();
			}
			ExperienceInfoList experienceInfo=(ExperienceInfoList) data.getExtras().get("experienceInfo");
			experienceInfoList.add(experienceInfo);
			return;
		}
		
		if(resultCode==RESULT_OK){
			switch (requestCode) {
			case GRAPH:
				GlideUtiles.loadIntoUseFitWidth(this, picPath, show_photo);
				certificatePhoto=Base64.encode(FileUtils.getBytes(picPath));
				break;

			case ALBUM:
				ContentResolver resolver = getContentResolver();  
				//照片的原始资源地址  
				Uri originalUri = data.getData();   
				try {  
					//使用ContentProvider通过URI获取原始图片  
					image = MediaStore.Images.Media.getBitmap(resolver, originalUri);  
					if (image != null) {  
						ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
						image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
						FileOutputStream fileOutputStream = null;
						File file=FileUtils.getPhotoFile();
						// 打开文件输出流
						fileOutputStream = new FileOutputStream(file);
						// 生成图片文件
						image.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
						// 相片的完整路径
						picPath=file.getPath();
						GlideUtiles.loadIntoUseFitWidth(this, picPath, show_photo);
						certificatePhoto=Base64.encode(baos.toByteArray());
						destoryBimap();
					}  
				} catch (IOException e) {  
					e.printStackTrace();  
				}    
				break;
				
			case 2:
				
				break;

			default:
				break;
			}
		}else{
			showShortToast("获取照片出错，请重试");
		}
		
	}

	/**
	 * 销毁图片文件
	 */
	private void destoryBimap()
	{
		if (image != null && ! image.isRecycled()) {
			image.recycle();
			image = null;
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
//		super.onBackPressed();
		intent=new Intent(QualificationActivity.this, CetificationActivity.class);
		startActivity(intent);
		finish();
		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);

	}
}
